package com.gnerv.author.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gnerv.author.entity.FileManage;
import com.gnerv.author.mapper.FileMapper;
import com.gnerv.author.service.IFileService;
import com.gnerv.author.util.CommonUtil;
import com.gnerv.author.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/7/25
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileManage> implements IFileService {

    @Autowired
    FileMapper fileMapper;


    @Override
    public FileManage save(MultipartFile file) throws IOException {
        String path = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+ "/public/file";
        String bId = UUIDUtil.getLower();
        String fileOriginalFilename = file.getOriginalFilename();
        String name = bId + "." + CommonUtil.getFileSuffix(fileOriginalFilename);
        File fileObj = new File(path, name);
        FileCopyUtils.copy(file.getBytes(), fileObj);
        FileManage fileManage = new FileManage();
        fileManage.setbId(bId);
        fileManage.setName(fileOriginalFilename);
        fileManage.setSuffix(CommonUtil.getFileSuffix(fileOriginalFilename));
        fileManage.setSize(file.getSize());
        fileManage.setPath(fileObj.getPath());
        fileManage.setUrl("/public/file/" + name);
        fileMapper.insert(fileManage);
        return fileManage;
    }

    @Override
    public FileManage save(MultipartFile file, FileManage fileManage) {
        return null;
    }

    @Override
    public FileManage select(String bId) {
        FileManage fileManage = fileMapper.selectOne(new QueryWrapper<>(new FileManage(bId)));
        return fileManage;
    }

    @Override
    public File download(String bId) {
        FileManage fileManage = fileMapper.selectOne(new QueryWrapper<>(new FileManage(bId)));
        File file = new File(fileManage.getPath());
        return file;
    }

}
